package com.lingx.service.query;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.lingx.model.IContext;
import com.lingx.model.IPerformer;
import com.lingx.model.impl.DefaultEntity;
import com.lingx.model.impl.DefaultField;
import com.lingx.service.ModelService;
import com.lingx.utils.Utils;
import com.lingx.web.api.IApi;

@Component
public class CascadeCondition implements IGridCondition{
	@Resource
	private ModelService modelService;

	@Override
	public String getCondition(Map<String, Object> params, IContext context, IPerformer performer) {

		String ecode=context.getEntity().getCode();
		String refEntity=IApi.getParamString(params, "_refEntity_", "");//getRequest().getParameter("_refEntity_");
		String refId=IApi.getParamString(params, "_refId_", "");//context.getRequest().getParameter("_refId_");
		String rule=IApi.getParamString(params, "rule", "");//context.getRequest().getParameter("rule");
		if(Utils.isNull(rule)||"_none_".equals(rule)) {//一级级联
			StringBuilder sb=new StringBuilder();
			List<DefaultField> fields=context.getEntity().getFields().getList();
			for(DefaultField field:fields) {
				if(Utils.isNotNull(field.getRefEntity())&&params.containsKey(field.getCode())) {
					sb.append(" and ").append(field.getCode()).append("=").append("'").append(params.get(field.getCode()).toString()).append("'");
				}
			}
			return sb.toString();
		}else {//二级级联
			StringBuilder sb=new StringBuilder();
			DefaultEntity entity=modelService.getEntity(rule);
			//System.out.println(rule+","+ecode);
			//System.out.println(rule+","+refEntity);
			String valueFieldCode=modelService.getFieldByEntity(entity, ecode).getCode();
			String tiaojianFieldCode=modelService.getFieldByEntity(entity, refEntity).getCode();
			sb.append(" and ").append(modelService.getValueField(context.getEntity())).append(" in (");
			sb.append(this.getCascadeRule_1(valueFieldCode, entity.getTableName(), tiaojianFieldCode, refId));
			sb.append(") ");
			return sb.toString();
		}
	}

	/**
	 * 
	 * @param valueField 值
	 * @param tableName 表
	 * @param tianjianField 条件字段
	 * @param tianjian 条件
	 * @return
	 */
	private String getCascadeRule_1(String valueField,String tableName,String tiaojianField,String tiaojian){
		StringBuilder sb=new StringBuilder();
		sb.append("select ").append(valueField).append(" from ").append(tableName).append(" where ").append(tiaojianField).append(" in ('").append(tiaojian).append("')");
		return sb.toString();
	}
}
